﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Globalization;

namespace Travel.Api.Site
{
    public partial class OptionChoicePage : BaseDataPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }

        }

        protected void grid_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PackageDestinationOption item = (PackageDestinationOption)e.Item.DataItem;
                
                DropDownList ddl = (DropDownList)e.Item.FindControl("ddlOptionChoice");
                
                OptionChoice ochEmpty = new OptionChoice();
                ochEmpty.ChoiceId = -1;
                ochEmpty.ChoiceDescription = "(select option value)";
                    
                var choices = item.Choices.ToList();
                choices.Insert(0, ochEmpty);

                ddl.DataSource = choices;
                ddl.DataBind();
            }
        }


        public override void LoadData()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ApiTravelPackageRepository>())
            {
                var options = repo.FindOptions(PkgDestId, TravelId);
                if (options.Where(i => i.SelectedChoiceId != -1).Count() > 0)
                {
                    Response.Redirect(string.Format("OptionChoiceView.aspx?pdid={0}&tid={1}", PkgDestId.ToString(), TravelId.ToString()), true);
                }
                else
                {
                    grid.DataSource = options;
                }
                
                grid.DataBind();
            }

            txtStartDate.Text = DateTime.Today.AddDays(1).ToString("d", new CultureInfo("en-US"));
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            LoadData();
            txtStartDate.Text = "";
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string choiceIdArr = "";
            string script = "";

            using (var repo = RepositoryFactory.ResolveRepository<ApiTravelPackageRepository>())
            {
                var options = repo.FindOptions(PkgDestId, TravelId);

                foreach (RepeaterItem ri in grid.Items)
                {
                    string choiceId = ((DropDownList)ri.FindControl("ddlOptionChoice")).SelectedValue;
                    string optionId = ((HiddenField)ri.FindControl("hidId")).Value;

                    if (!string.IsNullOrEmpty(choiceIdArr))
                        choiceIdArr += ",";
                    choiceIdArr += choiceId.ToString();

                    PackageDestinationOption updItem = options.Where(i=>i.OptionId == Convert.ToInt32(optionId)).SingleOrDefault();
                    if (updItem != null)
                        updItem.SelectedChoiceId = Convert.ToInt32(choiceId);
                }

                if (options.Where(i => i.SelectedChoiceId == -1).Count() > 0)
                {
                    script = string.Format("alert('{0}'); ", "Not all option chosen!");
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                    return;
                }

                DateTime startDate;
                try
                {
                    startDate = DateTime.ParseExact(txtStartDate.Text, "d", new CultureInfo("en-US"));
                    TravelPackage tp = repo.FindClientPackage(TravelId); 
                    if ((tp.ExpDate.HasValue) && (tp.VacationLength.HasValue))
                        if (tp.ExpDate.Value.AddDays(-tp.VacationLength.Value) < startDate)
                        {
                            script = string.Format("alert('{0}'); ", "Date must be before ExpDate minus Vac. Lenght days!");
                            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                            return;
                        }
                }
                catch (Exception e1)
                {
                    script = string.Format("alert('{0}'); ", "Date not valid!");
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                    return;
                }
                
                int result = repo.SetPkgChoice(TravelId, ContactId, PkgDestId, choiceIdArr, startDate);
                if (result == 0)
                    Response.Redirect("~/Client/TravelPackage.aspx");
                else
                {
                    script = string.Format("alert('{0}'); ", Common.GetEnumDescription((ErrorCodes)result));
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                }
                
            }
        }

        public int PkgDestId
        {
            get
            {
                int result = -1;
                if (!string.IsNullOrEmpty(Request.QueryString["pdid"]))
                    result = Convert.ToInt32(Request.QueryString["pdid"]);
                return result;
            }
        }

        public int TravelId
        {
            get
            {
                int result = -1;
                if (!string.IsNullOrEmpty(Request.QueryString["tid"]))
                    result = Convert.ToInt32(Request.QueryString["tid"]);
                return result;
            }
        }
    }
}